<template>
  <div class="match-record-detail-container">
    <a-spin :spinning="loading">
      <a-alert v-if="error" type="error" show-icon>{{ error }}</a-alert>
      <a-descriptions v-else :column="{ xs: 1, sm: 2 }" bordered>
        <!-- 基础信息 -->
        <a-descriptions-item label="Match ID">{{ record?.matchId }}</a-descriptions-item>
        <a-descriptions-item label="Opponent Name">{{ record?.opponentName }}</a-descriptions-item>
        <a-descriptions-item label="Position">{{ record?.position }}</a-descriptions-item>
        <a-descriptions-item label="Match Date">
          {{ formatDate(record?.matchDate) }}
        </a-descriptions-item>
        <a-descriptions-item label="Knockout Time">{{ record?.knockoutTime }}</a-descriptions-item>
        <a-descriptions-item label="Result">{{ record?.result }}</a-descriptions-item>

        <!-- 上半场详情 -->
        <a-descriptions-item label="First Half Score">{{ record?.firstHalfScore }}</a-descriptions-item>
        <a-descriptions-item label="First Half My Lost">{{ record?.firstHalfMyLost }}</a-descriptions-item>
        <a-descriptions-item label="First Half Opponent Lost">{{ record?.firstHalfOpponentLost }}</a-descriptions-item>
        <a-descriptions-item label="First Half Lost Sets">{{ record?.firstHalfLostSets }}</a-descriptions-item>
        <a-descriptions-item label="First Half Comments">
          <div class="comment-section">
            <a-button type="primary" @click="showModal('first')">+ Add Comment</a-button>
            <!-- 上半场评论 -->
            <div class="comment-list">
              <Comment :comments="firstHalfComments" /> <!-- 绑定 firstHalfComments -->
            </div>
          </div>
        </a-descriptions-item>

        <!-- 下半场详情 -->
        <a-descriptions-item label="Second Half Score">{{ record?.secondHalfScore }}</a-descriptions-item>
        <a-descriptions-item label="Second Half My Lost">{{ record?.secondHalfMyLost }}</a-descriptions-item>
        <a-descriptions-item label="Second Half Opponent Lost">{{ record?.secondHalfOpponentLost }}</a-descriptions-item>
        <a-descriptions-item label="Second Half Lost Sets">{{ record?.secondHalfLostSets }}</a-descriptions-item>
        <a-descriptions-item label="Second Half Comments">
          <div class="comment-section">
            <a-button type="primary" @click="showModal('second')">+ Add Comment</a-button>
            <div class="comment-list">
              <Comment :comments="secondHalfComments" /> 
            </div>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      <div class="action-bar">
        <a-button @click="goBack">Back to List</a-button>
      </div>
    </a-spin>
    <a-drawer
      v-model:open="isModalVisible"
      title="Add Comment"
      placement="right"
      :width="600"
      :footer-style="{ textAlign: 'right' }"
    >
      <a-form :model="newComment" layout="vertical">
        <a-form-item label="Username" required>
          <a-input v-model:value="newComment.author" placeholder="Auto-filled Username" :disabled="true"/>
        </a-form-item>
        <a-form-item label="Comment Content" required>
          <a-textarea
            v-model:value="newComment.content"
            placeholder="Enter comment content"
            :rows="4"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="submitComment">Submit</a-button>
        </a-form-item>
      </a-form>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import axios from '../axios'; // 假设已配置axios实例
import Comment from '../components/Comment.vue';
import dayjs from 'dayjs';
import { useAuthStore } from '../store/auth';
// 引入 extractUsernameFromToken 方法
import { extractUsernameFromToken } from '../utils/tokenUtils';

interface CommentItem {
  id: string;
  author: string;
  content: string;
  datetime: string;
  halfType: 'first' | 'second' | null; // 新增类型定义
}
interface MatchDetail {
  matchId: number;
  opponentName: string;
  position: string;
  matchDate: string;
  knockoutTime: string;
  result: string;
  firstHalfScore: string;
  firstHalfMyLost: string;
  firstHalfOpponentLost: string;
  firstHalfLostSets: string;
  secondHalfScore: string;
  secondHalfMyLost: string;
  secondHalfOpponentLost: string;
  secondHalfLostSets: string;

}

const authStore = useAuthStore();
const route = useRoute();
const router = useRouter();
const loading = ref(true);
const error = ref('');
const isModalVisible = ref(false);
const commentType = ref<'first' | 'second'>('first');
const newComment = ref<CommentItem>({
  id: '',
  author: '',
  content: '',
  datetime: '',
  halfType: null,
});
const record = ref<MatchDetail>({
  matchId: 0,
  opponentName: '',
  position: '',
  matchDate: '',
  knockoutTime: '',
  result: '',
  firstHalfScore: '',
  secondHalfScore: '',
  secondHalfMyLost: '',
  secondHalfOpponentLost: '',
  secondHalfLostSets: '',
  firstHalfMyLost: '',
  firstHalfOpponentLost: '',
  firstHalfLostSets: ''
});
// 在组件顶部新增两个 ref 变量
const firstHalfComments = ref<CommentItem[]>([]);
const secondHalfComments = ref<CommentItem[]>([]);

const fetchMatchDetail = async () => {
  try {
    loading.value = true;
    const matchId = route.params.matchId as string;
   
    
    // 获取比赛基础信息
    const detailRes = await axios.get(`/matchs/${matchId}`);
    record.value = detailRes.data.data;



  } catch (err) {
    error.value = '获取比赛详情失败';
  } finally {
    loading.value = false;
  }
};

const fetchMatchCommentDetail = async () => {
  try {
    const matchId = route.params.matchId as string;
    
    // 获取对应id评论（假设后端返回包含halfType字段）
    const commentsRes = await axios.get(`/matchs/${matchId}/comments/${matchId}`);
    const allComments = commentsRes.data.data;
    
    // 分离评论并存储到独立变量
    firstHalfComments.value = allComments.filter(
      (comment: CommentItem) => comment.halfType === 'first'
    );
    secondHalfComments.value = allComments.filter(
      (comment: CommentItem) => comment.halfType === 'second'
    );

    // console.log(firstHalfComments.value)
    // console.log(secondHalfComments.value)

  } catch (error) {
    console.error('获取评论失败:', error);
  }
};
const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm');
};

const showModal = (type: 'first' | 'second') => {
  commentType.value = type;
  isModalVisible.value = true;

  // 新增：获取用户角色
  const role = authStore.isAdmin 
    ? 'admin' 
    : authStore.isCoach 
      ? 'coach' 
      : authStore.isGuest 
        ? 'guest' 
        : 'user';

  newComment.value = {
    id: '',
    // 修改：拼接角色信息
    author: `${role}: ${extractUsernameFromToken(authStore.token || '')}`,
    content: '',
    datetime: '',
    halfType: commentType.value,
  };
};

const submitComment = async () => {
  try {
    if (!newComment.value.author || !newComment.value.content) {
      message.error('Author and content cannot be empty');
      return;
    }
    const matchId = route.params.matchId as string;
    const url = `/matchs/${matchId}/comments/${matchId}`;

    const res = await axios.post(url, {
      matchId:matchId,
      author: newComment.value.author,
      content: newComment.value.content,
      // 在submitComment方法中
      datetime: dayjs().format('YYYY-MM-DDTHH:mm:ss'), // 新格式
      halfType: commentType.value, // 必须包含 halfType
    });

    // 更新对应半场的评论列表
    const comment = res.data.data;
    if (comment.halfType === 'first') {
      firstHalfComments.value.push(comment);
    } else {
      secondHalfComments.value.push(comment);
    }

    isModalVisible.value = false;
    message.success('Comment submitted successfully');
    resetForm();
  } catch (err: any) {
    message.error(err.response?.data.message || 'Submission failed');
  }
};

const resetForm = () => {
  newComment.value = {
    id: '',
    author: '',
    content: '',
    datetime: '',
    halfType: null,
  };
};

const goBack = () => {
  router.push({ name: 'MatchRecord' });
};

onMounted(() => {
  fetchMatchDetail();
  fetchMatchCommentDetail();
});
</script>


// const mockData = {
//   '1': {
//     opponentName: 'Team A',
//     position: '主',
//     matchDate: '2023-10-01',
//     knockoutTime: '45:00',
//     result: '胜 (3-1)',
//     firstHalfScore: '2-0',
//     secondHalfScore: '1-1',
//     firstHalfMyLost: '0',
//     firstHalfOpponentLost: '2',
//     firstHalfLostSets: '0局',
//     firstHalfComment: [
//       {
//         id: '1-1',
//         author: '教练',
//         content: '防守稳固，控球占优',
//         datetime: dayjs().subtract(1, 'days'),
//       },
//       {
//         id: '1-2',
//         author: '教练',
//         content: '中场拦截效率高',
//         datetime: dayjs().subtract(0.8, 'days'),
//       }
//     ],
//     secondHalfComment: [
//       {
//         id: '2-1',
//         author: '队长',
//         content: '下半场进攻节奏加快，但防守漏洞增多',
//         datetime: dayjs().subtract(0.5, 'days'),
//       },
//       {
//         id: '2-2',
//         author: '助理教练',
//         content: '边路传中质量下降，需加强体能训练',
//         datetime: dayjs().subtract(0.3, 'days'),

//       }
//     ]
//   },
// };





<style scoped>
.match-record-detail-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.comment-container {
  max-width: 100%;
  /* 其他样式保持不变 */
}
</style>